import { apiProxy } from "@/utils/request";

export default {
    state: {
        userToken: localStorage.getItem("userToken"),
        userInfo: JSON.parse(localStorage.getItem("userInfo"))
    },
    getters: {
        getUserInfo(state) {
            return state.userInfo
        }
    },
    mutations: {
        clearUser(state) {
            state.userToken = null;
            state.userInfo = null;
            localStorage.removeItem("userToken");
            localStorage.removeItem("userInfo");
        },
        login(state, res) {
            state.userToken = res.token;
            state.userInfo = res.user

            localStorage.setItem("userToken", res.token);
            localStorage.setItem("userInfo", JSON.stringify(res.user))
        }
    },
    actions: {
        clearUserAsync({ commit }) {
            return new Promise((resolve) => {
                commit("clearUser");
                resolve("清除用户成功")
            })
        },
        loginAsync({ commit }, data) {
            return new Promise(resoleve => {
                // vuex中不能用this，需要引入apiProxy使用
                apiProxy({
                    url: "/api/login",
                    method: "post",
                    data
                }).then(res => {
                    commit("login", res)
                    resoleve(res);
                })
            })

        }
    },
    modules: {
    }
}
